//index.js
//获取应用实例
const app = getApp()
var EXPayPublic = require('../../utils/EXPayPublic.js');

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    openId:'',
    percent:0,
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  paySuccess:function(){

  },
  onLoad: function () {
     

    wx.setNavigationBarTitle({
      title:"小程序支付"
    });
    var that = this 
    wx.login({
      success: res => {
        console.log("code:"+res.code)
        wx.request({
          url: 'https://weixin.iappsw.cn/pay/openId.html',
          data: {
            appId: 'wxa095e06a92f8d952',
            jsCode: res.code
          },
          success (res) {
            console.log("openId:"+res.data.openid)
            that.setOpenId(res.data.openid)
          },
          fail (res) {
            console.log("失败",res)
          }
        })
      }
    })
 
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  pay:function(e){
    var that = this
    wx.showLoading({
      title: '支付请求中',
    })

    console.log("id" + JSON.stringify(e.currentTarget.id))
    console.log(that.data.openId)
    if(that.data.openId.length>0){
      var payParams = {
        merchantOrderId: new Date().getTime() + "",
        orderName: "测试",
        orderDesc: "测试",
        orderDate: new Date().getTime() + "",
        tradeAmount: e.currentTarget.id,
        openId: that.data.openId
      };
      EXPayPublic.doEXPay(payParams, function (data) {
        console.log("支付成功", data)
      }, function (data) {
        console.log("支付失败", data)
      }, function (data) {
        console.log("支付完成", data)
      });
     
    }else{
      wx.showToast({
        title:"重新刷新页面进行授权",
        icon: 'none',
        duration: 2000
      })
    }
    
  
  },
  setOpenId:function(openId){
    this.setData({
      openId: openId
    })
  }
})
